import {apiPrefix} from '../decorator/router'
import request from 'request'
const nodeUrl = require('url')

// qq音乐地址转发
export function transmit(app) {
  app.use(async (ctx, next) => {
    const url = ctx.request.url
    const keyword = `${apiPrefix}/transmit/`
    if (url.indexOf(keyword) === 0) {
      ctx.respond = false
      const id = decodeURIComponent(url.replace(new RegExp(keyword), ''))
      const u = nodeUrl.parse(id)
      const trans = request({
        method: ctx.request.method,
        url: u.href,
        headers: {
          referer: 'https://m.y.qq.com/',
          origin: 'https://m.y.qq.com'
        }
      })
      ctx.req.pipe(trans).on('error', e => {
        ctx.res.end(JSON.stringify({
          result: 0,
          message: e.message
        }))
      })
      trans.pipe(ctx.res)
      trans.on('response', (response) => {
        response.headers['access-control-allow-origin'] = '*'
      })
      trans.on('error', e => {
        ctx.res.end(JSON.stringify({
          result: 0,
          message: e.message
        }))
      })
    } else {
      await next()
    }
  })
}
